package com.marktotop.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.marktotop.entity.*;
import com.marktotop.response.ResultBean;
import com.marktotop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author marktotop
 * @since 2021-05-23
 */
@RestController
@Api(tags = "员工管理")
@RequestMapping("/employee/basic")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPoliticsStatusService politicsStatusService;
    @Autowired
    private IJoblevelService joblevelService;
    @Autowired
    private INationService nationService;
    @Autowired
    private IPositionService positionService;
    @Autowired
    private IDepartmentService departmentService;


    /**
     * 获取全部员工(分页)
     *
     * @param currentPage
     * @param size
     * @param employee
     * @param
     * @return
     */
    @ApiOperation(value = "获取全部员工(分页)")
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public ResultBean getEmployee(@RequestParam(defaultValue = "1") Integer currentPage,
                                  @RequestParam(defaultValue = "10") Integer size,
                                  Employee employee,
                                  LocalDate[] beginDateScope) {
        return employeeService.getEmployeeByPage(currentPage, size, employee, beginDateScope);

    }

    /**
     * 获取所有的政治面貌
     * @return
     */
    @ApiOperation(value = "获取所有的政治面貌")
    @RequestMapping(value = "/politicsstatus",method = RequestMethod.GET)
    public List<PoliticsStatus> getAllPoliticsStatus() {
        return politicsStatusService.list();
    }

    /**
     * 获得所有职称
     * @return
     */
    @ApiOperation(value = "获得所有职称")
    @RequestMapping(value = "/joblevels",method = RequestMethod.GET)
    public List<Joblevel> getAllJoblevels() {
        return joblevelService.list();
    }

    /**
     * 获取所有民族
     * @return
     */
    @ApiOperation(value = "获取所有民族")
    @RequestMapping(value = "/nations",method = RequestMethod.GET)
    public List<Nation> getAllNations() {
        return nationService.list();
    }

    /**
     * 获取所有职位
     * @return
     */
    @ApiOperation(value ="获取所有职位")
    @RequestMapping(value = "/postions",method = RequestMethod.GET)
    public List<Position> getAllPostions() {
        return positionService.list();
    }

    /**
     * 获取所有部门
     * @return
     */
    @ApiOperation(value="获取所有部门")
    @RequestMapping(value = "/deps",method = RequestMethod.GET)
    public List<Department> getAllDepartments() {
        return departmentService.getAllDepartment();
    }

    /**
     * 获取工号
     * @return
     */
    @ApiOperation(value = "获取工号",notes = "获取工号")
    @RequestMapping(value = "/maxWorkID",method = RequestMethod.GET)
    public ResultBean maxWorkID() {
        String maxWorkID = employeeService.maxWorkID();
        if (null != maxWorkID) {
            return ResultBean.ok().message("获取工号，成功").data("maxWorkID",maxWorkID);
        }
        return ResultBean.error().message("获取工号，失败");
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @ApiOperation(value = "添加员工",notes = "POST方式添加员工信息")
    @RequestMapping(value = "/",method = RequestMethod.POST)
    public ResultBean addEmp(@RequestBody Employee employee) {
        return employeeService.addEmp(employee);
    }

    @ApiOperation(value = "更新员工",notes = "PUT更新员工信息")
    @RequestMapping(value = "/",method = RequestMethod.PUT)
    public ResultBean updateEmp(@RequestBody Employee employee) {
        if (employeeService.updateById(employee)) {
            return ResultBean.ok().message("员工信息更新成功！");
        }
        return ResultBean.error().message("员工信息更新失败！");
    }

    @ApiOperation(value = "删除员工",notes = "DELETE方式删除员工信息")
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public ResultBean deleteEmp(@PathVariable Integer id) {
        if (employeeService.removeById(id)) {
            return ResultBean.ok().message("员工信息删除成功！");
        }
        return ResultBean.error().message("员工信息删除失败！");
    }

    @ApiOperation(value = "导出全部员工信息excel")
    @GetMapping(value = "/export/",produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response){
        List<Employee> list = employeeService.getEmployee(null);
        //设置excel表
        /*
        HSSF  03.xls
        XSSF  07.xlsx
         */
        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.XSSF);
        //设置工作簿
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list);
        ServletOutputStream out=null;
        try {
            //流形式传送
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码content-disposition
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder
                    .encode("员工表.xlsx","UTF-8"));
            out= response.getOutputStream();
             workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        ResultBean.error().message("员工信息导出失败!");
        }
        finally {
            try {
                if (null!=out){
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
         ResultBean.ok().message("员工信息导出操作成功！");
        }

    }

    @ApiOperation(value = "导入员工信息")
    @PostMapping(value = "/import/")
    public ResultBean importEmployee(MultipartFile file){
        ImportParams params = new ImportParams();
        //设置标题行 忽略
        params.setTitleRows(1);
        List<Employee> list=null;
        List<Nation> nationList = nationService.list();
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
        List<Department> departmentList = departmentService.list();
        List<Joblevel> joblevelList = joblevelService.list();
        List<Position> positionList = positionService.list();
        try {
            list= ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
           list.forEach(employee -> {
               //设置民族id
               //list indexOf 返回索引值
               //nationList.indexOf(new Nation(employee.getNation().getName()))
               employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
               //设置员工id
               employee.setDepartmentId(departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName()))).getId());
               //设置政治面貌id
               employee.setPoliticId(politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
               //设置职位id
               employee.setPosId(positionList.get(positionList.indexOf(new Position(employee.getPosition().getName()))).getId());
                //设置职称id
               employee.setJobLevelId(joblevelList.get(joblevelList.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
           });
           //保存到数据库
           if (employeeService.saveBatch(list)){
             return  ResultBean.ok().message("员工信息导入成功！");
           }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultBean.error().message("员工信息导入失败！");
    }
}
